package com.kds.smarthome.controller;

import com.kds.smarthome.common.AjaxResponse;
import com.kds.smarthome.entity.LoginInfo;
import com.kds.smarthome.service.LoginInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统访问记录控制器
 */
@RestController
@RequestMapping("/api/system/logininfor")
public class LoginInfoController {
    
    @Autowired
    private LoginInfoService loginInfoService;
    
    /**
     * 获取登录日志列表
     */
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/list")
    public AjaxResponse list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                            @RequestParam(value = "loginName", required = false) String loginName,
                            @RequestParam(value = "status", required = false) String status,
                            @RequestParam(value = "ipaddr", required = false) String ipaddr,
                            @RequestParam(value = "beginTime", required = false) String beginTime,
                            @RequestParam(value = "endTime", required = false) String endTime) {
        
        Map<String, Object> params = new HashMap<>();
        params.put("offset", (pageNum - 1) * pageSize);
        params.put("pageSize", pageSize);
        params.put("loginName", loginName);
        params.put("status", status);
        params.put("ipaddr", ipaddr);
        params.put("beginTime", beginTime);
        params.put("endTime", endTime);
        
        List<LoginInfo> list = loginInfoService.selectLoginInfoList(params);
        long total = loginInfoService.count(params);
        
        Map<String, Object> data = new HashMap<>();
        data.put("rows", list);
        data.put("total", total);
        
        return AjaxResponse.success(data);
    }
    
    /**
     * 批量删除日志
     */
    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/{infoIds}")
    public AjaxResponse remove(@PathVariable Long[] infoIds) {
        int rows = loginInfoService.deleteLoginInfoByIds(infoIds);
        return AjaxResponse.success("成功删除" + rows + "条记录");
    }
    
    /**
     * 清空日志
     */
    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/clean")
    public AjaxResponse clean() {
        loginInfoService.cleanLoginInfo();
        return AjaxResponse.success("清空登录日志成功");
    }
} 